package com.wan.personnel2.web.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wan.personnel2.common.Const;
import com.wan.personnel2.entity.UserInf;
import com.wan.personnel2.service.UserInfService;
import com.wan.personnel2.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;

/**
 * @author anning
 */
@Controller
@RequestMapping("/userInf")
public class UserInfController {

    @Autowired
    private UserInfService service;


    @RequestMapping("/login")
    public String doLogin(String loginname, String password, HttpSession session, Model model) throws NoSuchAlgorithmException {
        UserInf user = service.dologin(loginname,password);
        if (user != null) {
            session.setAttribute(Const.IS_LOGIN,user);
            //重定向到首页
            return "redirect:/index.jsp";

        }
        //登录失败
//        model.addAttribute("message","登录失败");
        model.addAttribute("message","登录失败");
        return "loginForm";
    }

    @RequestMapping("/list")
    public String getUserList(String loginname,Integer pageNum,Model model){
        IPage<UserInf> page = service.getUserPageWithName(loginname,pageNum==null?1:pageNum);
        model.addAttribute("page",page);
        model.addAttribute("loginname",loginname);
        return "user/list";
    }

    @RequestMapping("/del/{id}")
    @ResponseBody
    public boolean delUserInf(@PathVariable Integer id){
        boolean ans = service.delUserInf(id);
        return ans;
    }

    @RequestMapping("/add")
    @ResponseBody
    public boolean addUserInf(@RequestBody UserInf user) throws NoSuchAlgorithmException {
        boolean ans = service.addUserInf(user);
        return ans;
    }

    @RequestMapping("/getUserById")
    public String getUserById(Integer id,Model model){
        UserInf user = service.getById(id);
        if (user != null) {
            model.addAttribute("user",user);
            return "user/myupdate";
        }
        return "redirect:/userInf/list";
    }

    @RequestMapping("/update")
    @ResponseBody
    public boolean update(@RequestBody UserInf userInf) throws NoSuchAlgorithmException {
//        设置密码的长度
        if (userInf.getPassword().length()<10) {
            userInf.setPassword(MD5Utils.repeat(userInf.getPassword(),userInf.getUsername()));

        }
        boolean b = service.updateById(userInf);
        return b;
    }

}
